<?php

namespace App\Controller\Common;

use App\Base\BaseConfig;
use App\Base\BaseController;
use App\Entity\Message;
use App\Model\MessageModel;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;


/**
 * @route("/p")
 */
class PrinterController extends BaseController
{
    /**
     * @route("/test",name="printTest")
     */
    public function printTest(){
        $data = array();
        $data["rnd"] = "?rnd=".uniqid();
        return $this->render("AppBundle:Test:index.html.twig",$data);
    }

    /**
     * @route("/deal",name="printDeal")
     */
    public function printDeal(){
        if(!$text = $this->getParamRequired("text")){return $this->json_out(0,"");}

        $rows  = mb_split("\n",$text);
        $data = array();
        $length = 0;

        $latter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $latters = str_split($latter);

        foreach ($rows as $key => $row) {
            if (!$row) {
                unset($rows[$key]);
            }

            $items = mb_split(",",$row);
            if ($key == 0) {
                $length = count($items);
                foreach ($items as $index => &$title) {
                    if ($index < 26) {
                        $str = $latters[$index];
                    } else {
                        $first = $latters[(int)floor($index/26) - 1];
                        $second = $latters[(int)floor($index%26)];
                        $str = $first.$second;
                    }
                    $title = "[".$str."]".$title;
                }
            } else {
                if (count($items) != $length) {
                    continue;
                }
            }
            $data[] = $items;
        }

        return $this->json_out(1,"123",$data);
    }

    /**
     * @route("/save/tpl",name="printSaveTpl")
     */
    public function printSaveTpl(){
        if(!$title = $this->getParamRequired("title")){return $this->json_out(0,"模板名称未设置");}
        if(!$data = $this->getParamRequired("data")){return $this->json_out(0,"参数错误，请刷新后重试");}

        $MessageModel = new MessageModel($this->getDoctrine());
        $entity = $MessageModel->getByTitle($title);
        if ($entity) {
            return $this->json_out(0,"名称重复");
        }

        $entity = new Message();
        $entity->setAddTime(time())
            ->setContent($data)
            ->setTitle($title)
            ->setToAll(0)
            ->setToType(0)
            ->setToUser(0);
        $this->myEm()->persist($entity);
        $this->myEm()->flush();

        return $this->json_out(1,"模板已添加");
    }
}
